#include <QgsSimulation/SelectFeatureTools.h>

using SimulationCore::QgsSimulation::SelectFeatureTools;

SelectFeatureTools::SelectFeatureTools(QgsMapCanvas *mapcanvas, const QString &action)
	:QgsMapToolEmitPoint(mapcanvas),
	mapcanvas_(mapcanvas),
	m_rubberband_(new QgsRubberBand(mapcanvas, QgsWkbTypes::PolygonGeometry)),
	action_(action)
{
	this->crs_ = this->mapcanvas_->mapSettings().destinationCrs();

	QColor color(0, 0, 0, 0);
	this->m_rubberband_->setColor(color);
	this->m_rubberband_->setStrokeColor(Qt::gray);
	this->m_rubberband_->setWidth(2);

	this->m_isselecting_ = false;

}

void SelectFeatureTools::canvasPressEvent(QgsMapMouseEvent * e)
{
	if (e->button() == Qt::LeftButton && !this->m_isselecting_) {
		this->mapcanvas_->scene()->addItem(this->m_rubberband_);
		this->m_start_point_ = e->mapPoint();
		this->m_end_point = e->mapPoint();
		this->m_isselecting_ = true;
		this->m_rubberband_->setToGeometry(
			QgsGeometry::fromPolygonXY({
				{
					{ this->m_start_point_.x(),this->m_start_point_.y() },
					{ this->m_start_point_.x(),this->m_start_point_.y() }
				}
		}), this->crs_);
	}
}

void SelectFeatureTools::canvasMoveEvent(QgsMapMouseEvent * e)
{
	if (this->m_isselecting_) {
		this->m_end_point = e->mapPoint();
		this->m_rubberband_->setToGeometry(
			QgsGeometry::fromPolygonXY({
				{
					{ this->m_start_point_.x(),this->m_start_point_.y() },
					{ this->m_end_point.x(),this->m_start_point_.y() },
					{ this->m_end_point.x(),this->m_end_point.y() },
					{ this->m_start_point_.x(),this->m_end_point.y() },
					{ this->m_start_point_.x(),this->m_start_point_.y() }
				}
		}), this->crs_);
	}
}

void SelectFeatureTools::canvasReleaseEvent(QgsMapMouseEvent * e)
{
	if (this->m_isselecting_) {
		this->m_isselecting_ = false;
		this->mapcanvas_->scene()->removeItem(this->m_rubberband_);

		if (m_start_point_ != m_end_point) {
			auto geometry = QgsGeometry::fromPolygonXY({
				{
					{ this->m_start_point_.x(),this->m_start_point_.y() },
					{ this->m_end_point.x(),this->m_start_point_.y() },
					{ this->m_end_point.x(),this->m_end_point.y() },
					{ this->m_start_point_.x(),this->m_end_point.y() },
					{ this->m_start_point_.x(),this->m_start_point_.y() }
				}
			});

			emit drawGeometry(this->action_, QgsWkbTypes::Polygon, geometry);
		}
		else {
			auto geometry = QgsGeometry::fromPolygonXY({
				{
					{ this->m_start_point_.x(),this->m_start_point_.y() },
					{ this->m_start_point_.x(),this->m_start_point_.y() }
				}
			});
			emit drawGeometry(this->action_, QgsWkbTypes::Polygon, geometry);
		}
		points_.clear();
	}
}

void SelectFeatureTools::deactivate()
{
	QgsMapToolEmitPoint::deactivate();
}
